<template>
  <div>
    <el-menu class="el-menu-vertical-demo">

      <el-menu-item index="-1" :class="{'el-selected':selectedIndex==='首页'}" @click="handlerClick({menuTitle:'首页',menuUrl:'/index',menuId:-1})" style="margin-left: -50px;">
        <i class="el-icon-s-home"></i>
        <span slot="title">首页&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
      </el-menu-item>

      <el-submenu v-for="(menu) in menuList" :key="menu.menuId" :index="menu.menuId.toString()" style="margin-left: -50px;">
        <template slot="title">
          <i class="el-icon-user-solid"></i>
          <span>{{menu.menuTitle}}</span>
        </template>
        <el-menu-item-group>
          <el-menu-item :class="{'el-selected':selectedIndex===menu1.menuTitle}" :index="menu1.menuId.toString()" v-for="(menu1) in menu.menus" :key="menu1.menuId" @click="handlerClick(menu1)">{{menu1.menuTitle}}</el-menu-item>
        </el-menu-item-group>
      </el-submenu>

    </el-menu>
  </div>
</template>

<script>
  import StorageEventBus from '@/util/StorageEventBus.js'
  import {
    setEditableTabs,
    getEditableTabs,
    setMenuSelectedIndex,
    getMenuSelectedIndex
  } from '@/util/storage.js'
  import {
    getAllMenu
  } from '@/api/menuApi.js'
  export default {
    data() {
      return {
        menuList: [],
        selectedIndex: "首页"
      }
    },
    async created() {
      let res = await getAllMenu()
      this.menuList = res.data
      this.selectedIndex = getMenuSelectedIndex()?getMenuSelectedIndex():"首页"
    },
    mounted() {
      // 监听存储事件
      StorageEventBus.$on('storageChangedMenu', this.storageChangedMenu);
    },
    methods: {
      handlerClick(menu) {
        let tab = {
          title: menu.menuTitle,
          name: ++getEditableTabs().length+'',
          url: menu.menuUrl
        }
        setEditableTabs(tab)
        StorageEventBus.$emit('storageChanged');
        this.$router.push({name:menu.menuUrl})
        this.selectedIndex = menu.menuTitle
        setMenuSelectedIndex(menu.menuTitle)
      },
      storageChangedMenu(){
        this.selectedIndex = getMenuSelectedIndex()
      }
    }
  }
</script>

<style scoped>
  .el-menu-vertical-demo {
    background-color: rgb(211, 220, 230);
  }
  a {
    text-decoration: none;
    color: #333333;
  }
  .el-menu-item.is-active{
    color:black
  }
  .el-selected{
    background-color: rgb(236,245,255);
  }
</style>
